package dinosaur;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Cactus extends Barrier {

    private BufferedImage[] cactusGroup;
    private int i;
    private boolean delay = false;

    public Cactus(BufferedImage[] images, GamePane pane) {
        this.cactusGroup = images;
        super.setToPane(pane);

        //初始化，随机选取障碍组里的任意一个
        i = r.nextInt(7);
        setTempImage(cactusGroup[i]);
        setCactusY(i); //根据障碍物的大小不同，定位不同的高度
        setX(GamePane.FULL_WINDOW_WIDTH);
        System.out.println("Cactus[" + i + "] is coming.");
    }

    public Cactus(BufferedImage[] images, GamePane pane, boolean delay) {
        this(images, pane);
        this.delay = delay;
    }

    @Override
    public void run() {
        if (delay) {
            try {
                sleep(r.nextInt(1000) + 800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        while (DinosaurMain.state != DinosaurMain.GAME_OVER) {
            if (DinosaurMain.state == DinosaurMain.PLAYING) {
                roll();
            }
            pane.repaint();
        }
    }

    @Override
    public void roll() {

        long temp;

        if (getX() < -1 * getTempImage().getWidth()) {
            //当前障碍物消失，或时长到达一定阈值，生成新的障碍物

            if (delay) {
                threadSleep(r.nextInt(1000) + 800);
            }

            //间隔出现障碍物等待的时间（毫秒） long
            temp = (long) r.nextDouble();
            threadSleep(100 * temp);

            //选取新的障碍物下标
            if (DinosaurMain.speed < 7) //如果速度不是很快，就用前5个仙人掌
                i = r.nextInt(7);
            else
                i = r.nextInt(5) + 3; //速度够快了就全部任意选用，即可能会出现仙人掌群
            setCactusY(i);
            setTempImage(cactusGroup[i]);
            setX(GamePane.FULL_WINDOW_WIDTH);
            System.out.println("Cactus[" + i + "] is coming.");
        } else {
            setX(getX() - DinosaurMain.speed);//障碍物以speed向左移动
        }

        pane.repaint();
        threadSleep(10);
    }

    /*障碍物大小不同，坐标y的设置不同*/
    private void setCactusY(int i) {
        if (i < 4) {
            //前4个都是小的
            setY(GamePane.WINDOW_HEIGHT / 10 * 7 - 45);
        } else {
            //后面的是大的
            setY(GamePane.WINDOW_HEIGHT / 10 * 7 - getTempImage().getHeight() / 4 * 3);
        }
    }

    //    Rectangle methods
    public Rectangle boundCactus(){
        return new Rectangle(getX(),getY(),getBarryWidth(),getBarryHeigh());
    }

    public Rectangle boundCactusTrunk(){
//        仙人掌中间的主干
        return new Rectangle(getX()+getBarryWidth()/3,getY()+5,getBarryWidth()/3,getBarryHeigh()-5);
    }

    public Rectangle boundCactusBody(){
        return new Rectangle(getX()+5,getY()+getBarryHeigh()/4,getBarryWidth()-10,getBarryHeigh()/2);
    }
}
